#include "n32g031.h"
#include "stdio.h"
#include "stdint.h"
#include "DevicesFlash.h"


int8_t cFlashWriteDatas(uint32_t uiAddress, uint8_t *pucBuff, int32_t iLength)
{
    uint32_t i = 0, uiCnt = 0, *puiDataAddress = (uint32_t *)pucBuff;
    int8_t cError = 0;

    if((iLength < 0) || ((uiAddress + iLength) >= FLASH_USER_MAX_ADDR))
    {
        printf("cFlashWriteDatas uiAddress: %08X iLength: %d >= FLASH_USER_MAX_ADDR.\r\n", uiAddress, iLength);
        return 1;
    }

    /* Unlocks the FLASH Program Erase Controller */
    FLASH_Unlock();

    /* 每次写入4字节 */
    for(i = 0; i < iLength; i += 4)
    {
        /* erase the flash pages */
        if((uiAddress % FLASH_PAGE_SIZE) == 0)
        {
            uiCnt = 8;
            while((FLASH_EraseOnePage(uiAddress) != FLASH_COMPL) && (--uiCnt));

            if(uiCnt == 0)
            {
                printf("cFlashWriteDatas fmc_page_erase addr: 0x%08X error.\r\n", (unsigned int)uiAddress);
                cError |= 2;
                break;
            }
        }

        /* program flash */
        if(FLASH_ProgramWord(uiAddress, *puiDataAddress++) != FLASH_COMPL)
        {
            printf("cFlashWriteDatas HAL_FLASH_Program addr: 0x%08X error!\r\n", (unsigned int)uiAddress);
            cError |= 4;
            break;
        }

        uiAddress += 4;
    }

    /* Locks the FLASH Program Erase Controller */
    FLASH_Lock();

    return cError;
}

int8_t cFlashReadDatas(uint32_t uiAddress, uint8_t *pucBuff, int32_t iLength)
{
    if((iLength < 0) || ((uiAddress + iLength) >= FLASH_USER_MAX_ADDR))
    {
        printf("cFlashReadDatas uiAddress: %08X iLength: %d >= FLASH_USER_MAX_ADDR.\r\n", uiAddress, iLength);
        return 1;
    }

    /* Read Flash */
    while((iLength--) > 0)
    {
        *pucBuff++ = *(volatile uint8_t*)uiAddress++;
    }

    return 0;
}
